<template>
    <div class="doctorreviewedit">
        <Row>
            <Col class="padding-t" span="24">{{editTt}}</Col>
        </Row>
        <Form ref="formInline" :model="info" :rules="infoRules" inline class="juzhong" :label-width="120" label-position="right">
            <Row>
                <Col span="24">
                    <FormItem prop="nature" v-if="natureList.length>0" label="服务项目类型：">
                        <Select class="w-select" v-model="info.nature" @on-change="changeHospital" style='width:200px'>
                            <Option
                                v-for="item of natureList"
                                :key="item.id"
                                :value="item.id"
                                style='text-align:center;'
                            >{{item.name}}</Option>
                        </Select>
                    </FormItem>
                </Col>            
                <Col span="24">
                    <FormItem label="服务项目归属：" >
                        <fourLevelLinkage
                            @changeProvince="changeProvince"
                            @changeCity="changeCity"
                            @changeArea="changeArea"
                            @changeHospital="changeHospital"
                            :province="info.provinceId"
                            :city="info.cityId"
                            :area="info.areaId"
                            :hospital="info.hospitalId"
                            ref="fourLevelLinkage"
                        ></fourLevelLinkage>
                    </FormItem>
                </Col>           
                <Col span="24" >
                    <FormItem prop="serviceName" label="服务项目名称：">
                        <Input
                            class="w-input"
                            v-model="info.serviceName"
                            :maxlength="60"
                            placeholder="请输入服务项目名称"
                        />
                    </FormItem>
                </Col>            
                <Col span="24">
                    <FormItem prop="serviceDes" label="操作规范：">
                        <Input
                            class="w-input"
                            v-model="info.serviceDes"
                            type="textarea"
                            :maxlength="100"
                            placeholder="请填写具体操作规范"
                        />
                    </FormItem>
                </Col>          
                <Col span="24">
                    <FormItem prop="numberYear" label="年服务次数：">
                        <Select class="w-select" v-model="info.numberYear">
                            <Option
                                v-for="(item,index) of numberYear"
                                :value="item"
                                :key="index"
                                style='text-align:center;'
                            >{{item}}/次</Option>
                        </Select>
                    </FormItem>
                </Col>          
                <Col  span="24">
                    <FormItem prop="executingAgency" label="执行机构/医生：">
                        <Select class="w-select" v-model="info.executingAgency">
                            <Option
                                v-for="item of executingAgencyList"
                                :key="item.id"
                                :value="item.id"
                                style='text-align:center;'
                            >{{item.name}}</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="24">
                    <FormItem prop="amt" label="收费标准(单次)：">
                        <InputNumber class="w-number" 
                            v-model="info.amt" 
                            :max="999.99"
                            :min="0.01"
                            placeholder="请输入收费标准"
                        />
                    </FormItem>
                </Col>          
                <Col span="24">
                    <FormItem prop="governmentsubsidycost" label='政府补贴(单次)：'>
                        <InputNumber
                            class="w-number"
                            v-model="info.governmentsubsidycost"
                            :max="999.99"
                            :min="0.01"
                            placeholder="请输入政府补贴"
                        />
                    </FormItem>
                </Col>            
                <Col span="24">
                    <FormItem prop="packagestatus" label="是否启用：">
                        <img src="../../../assets/images/switchOK.png" alt="" v-if="info.packagestatus==1" @click="changeSwitch">
                        <img src="../../../assets/images/switchNO.png" alt="" v-if="info.packagestatus==0" @click="changeSwitch2">
                        <!-- <iSwitch v-model="info.packagestatus" :true-value="1" :false-value="0">
                            <span slot="open">是</span>
                            <span slot="close">否</span>
                        </iSwitch> -->
                    </FormItem>
                </Col>         
                <!--  服务关联表单 -->          
                <Col span="24">
                    <FormItem label="表单类型：" prop='formType'>
                        <Select class="w-select" v-model="info.formType" @on-change='fromTypeChange(info.formType)'>
                            <Option :value="0" key="无" style='text-align:center;'>暂不关联</Option>
                            <Option
                                v-for="(item,index) of formTypeList"
                                :value="Number(item.value)"
                                :key="index"
                                style='text-align:center;'
                            >{{item.title}}</Option>
                        </Select>
                    </FormItem>
                </Col>                        
                <Col span="24">
                    <FormItem label="关联内容：" prop='formRelation'>
                        <Select class="w-select" v-model="info.formRelation">
                            <Option :value="0" key="无" style='text-align:center;' v-if="info.formType != 1 ">无</Option>
                            <Option :value="0" key="国标慢病随访" style='text-align:center;' v-if="info.formType == 1 ">国标慢病随访</Option>
                            <Option
                                v-for="(item,index) of formContent"
                                :value="Number(item.id)"
                                :key="index"
                                style='text-align:center;'
                            >{{ item.title }}</Option>
                        </Select>
                    </FormItem>
                </Col>             
                <Col span="24">
                    <FormItem prop="remarks" label="备注：">
                        <Input
                            class="w-input"
                            v-model="info.remarks"
                            type="textarea"
                            placeholder="备注"
                            :maxlength="200"
                        />
                    </FormItem>
                </Col>              
                <Col span="24" style="text-align:center">
                    <Button style="width:75px;height:35px;" type="primary" :loading="saveBtnLoading" @click="submit('formInline')">
                        <Icon type="ios-checkmark" style="margin-right: 5px" />提交
                    </Button>
                    <Button style="width:75px;height:35px;" @click="reback">
                        <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>返回
                    </Button>
                </Col>
            </Row>
        </Form>
        <Spin fix v-if="showSpin"></Spin>
        <Modal
            title="系统提示："
            v-model="modalStatus"
            width="600"
            :mask-closable="false"
            footer-hide
        >
            <div style="font-size: 14px;margin-left: 20px;">
                <p>禁用服务项后会影响到：</p>
                <p>1、已计划的履约服务项不再执行；</p>
                <p>2、服务包中此服务项不再生效（添加履约计划时不在增加此服务项计划）；</p>
                <p>您确定要禁用此服务项吗？</p>
            </div>
            <div style='margin-top:10px;width:200px;margin:10px auto;'>
                <Button type="primary" @click="emigration" :disabled='disabledSave' class="btn">
                    <Icon type="ios-checkmark" style="margin-right: 5px" />确定
                </Button>
                <Button style="marginLeft: 20px" @click="back" class="btn">
                    <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
                </Button>
            </div>
        </Modal>
    </div>
</template>
<script>
import api from "@/api/commonApi";
import code from "@/configs/base.js";
import cookie from "@/utils/cookie.js";
import fourLevelLinkage from "@/components/fourLevelLinkage";
export default {
    components: {
        fourLevelLinkage
    },
    data() {
        return {
            disabledSave:false,
            modalStatus:false,
            showSpin: false,
            saveBtnLoading: false,
            id: null,
            info: {
                serviceName: null,
                // residentowncost: null,
                governmentsubsidycost: null,
                amt: null,
                packagestatus: 1,
                ascription: 1,
                hospitalId: null,
                serviceDes: null,
                provinceId: null,
                cityId: null,
                areaId: null,
                remarks: null,
                numberYear: 1,
                executingAgency: 1,
                nature: 1,
                formType: null,
                formRelation: null,
                // amountReceived: null
            },
            pageNo: null,
            numberYear: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
            natureList: [
                { id: 1, name: "增值付费项目" },
                { id: 2, name: "基本公共卫生服务承担项目" }
            ],
            executingAgencyList: [
                { id: 1, name: "服务中心" },
                { id: 2, name: "签约医院" }
            ],

            provinceList: [],
            provinceStatus: false,
            cityList: [],
            cityStatus: false,
            areaList: [],
            areaStatus: false,
            hospitalList: [],
            hospitalStatus: false,
            searchKey: "",
            hospitalId: "",
            identity: null,
            identityCoding: null,
            ownArea: null,

            infoRules: {
                serviceName: [
                    {
                        required: true,
                        message: "服务项目名称不能为空",
                        trigger: "change"
                    }
                ],
                amt: [
                    {
                        required: true,
                        type: 'number',
                        message: "收费标准不能为空",
                        trigger: "change"
                    }
                ],
                governmentsubsidycost: [
                    {
                        required: true,
                        type: 'number',
                        message: "政府补贴不能为空",
                        trigger: "change"
                    }
                ],
                formType: [
                    {
                        required: true,
                        type: 'number',
                        message: "关联表单不能为空",
                        trigger: "change"
                    }
                ],                
                formRelation: [
                    {
                        required: true,
                        type: 'number',
                        message: "关联内容不能为空",
                        trigger: "change"
                    }
                ],                                  
            },
            switch1: false,
            province: null,
            city: null,
            area: null,
            hospital: null,
            isBack: 2,
            // 服务关联表单
            formTypeList: [],
            // 关联内容
            formContent: []
        };
    },
    created() {
        this.province = this.$route.params.province
            ? parseInt(this.$route.params.province)
            : null;
        this.city = this.$route.params.city
            ? parseInt(this.$route.params.city)
            : null;
        this.area = this.$route.params.area
            ? parseInt(this.$route.params.area)
            : null;
        this.hospital = this.$route.params.hospital
            ? this.$route.params.hospital
            : null;
        this.pageNo = this.$route.params.pageNo
            ? parseInt(this.$route.params.pageNo)
            : 1;
            
        // 关联表单列表
        this.$axios.post(api.findSelection,{
        }).then(res => {
            if(res.data.success) {
                let ret = res.data.object;
                ret.forEach(item =>{
                    this.formTypeList.push({
                        value: Number(item.id),
                        title: item.name
                    })
                })
                console.log(this.formTypeList)
            } else {
                this.$Message.error("加载关联表单失败")
            }
        })
        let breadList = [
            { path: "/index", title: "首页" },
            {
                path: "/index/operation/servicePackage/pindex",
                title: "签约服务包"
            },
            {
                path: "/index/directory/serviceItems/list",
                title: "签约服务项"
            }
        ];
        this.$emit("changeBreadList", breadList);
    },
    mounted() {
        let id =this.$route.params.id;
        if (isNaN(id)) {
            this.editTt = `添加服务项目`;
        } else {
            this.editTt = `修改服务项目`;
            this.id = id;
            this.showSpin = true;
            this.$axios
                .post(api.getItemsById, { id: this.id })
                .then(resp => {
                    if (resp.data.object) {
                        this.info = JSON.parse(JSON.stringify(resp.data.object));
                        console.log(this.info)
                        if(this.info.amt){
                            this.info.amt = resp.data.object.amt
                        }
                        if(this.info.amt){
                            this.info.governmentsubsidycost = resp.data.object.governmentsubsidycost
                        }
                        if (this.info.provinceId) {
                            this.cityList = this.$store.getters.getCityList(
                                this.info.provinceId
                            );
                        }
                        if (this.info.cityId) {
                            this.areaList = this.$store.getters.getAreaList(
                                this.info.cityId
                            );
                        }
                        if(this.info.formType ==2) {
                            this.loadinghealArticle()
                        } else {
                            this.loadingFormContentList(this.info.formType)
                        }
                        // this.info.formType = Number(this.info.formType);
                        this.showSpin = false;
                    } else {
                        console.log("查询失败");
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        }
    },
    methods: {
        changeSwitch() {
            this.modalStatus = true
            this.disabledSave = false
        },
        emigration() {
            this.disabledSave = true
            this.info.packagestatus=0
            this.modalStatus = false
        },
        changeSwitch2() {
            this.info.packagestatus=1
        },
        back() {
            this.modalStatus = false
        },
        // 通过关联表单加载关联内容数据
        fromTypeChange (val) {
            this.info.formRelation = null;           
            if(val ==2) {
                this.loadinghealArticle()
            } else {
                this.loadingFormContentList(val)
            }
        },
        // 加载关联内容数据
        loadingFormContentList (id) {
            this.formContent = [];
            let params = {
                hospitalId: this.info.hospitalId,
                pattern: this.info.formType
            }
            if(!Boolean(this.info.hospitalId)) {
                this.$Message.info("请先选择医院后再查看关联表单数据!")
                return ""
            }
            this.$axios.post(api.findFormListByPattern, params).then(res => {
                if(res.data.success) {
                    let ret = res.data.object;
                        ret.forEach(item => {
                            this.formContent.push({
                                id: Number(item.id),
                                title: item.formName
                            });
                        })
                } else {
                    this.$Message.error(res.data.message);
                }
                this.info.formRelation = Number(this.info.formRelation);
                this.info.formType = Number(this.info.formType);
            })
        },
        //获取健康宣教文章
        loadinghealArticle() {
            this.formContent = [];
            let params = {
                pageNo: 1,
                pageSize: 10000
            }
            if(!Boolean(this.info.hospitalId)) {
                this.$Message.info("请先选择医院后再查看关联表单数据!")
                return ""
            }
            this.$axios.post(api.findhealArticle, params).then(res => {
                if(res.data.success) {
                    let ret = res.data.object.records;
                        ret.forEach(item => {
                            this.formContent.push({ 
                                id: Number(item.id),
                                title: item.title
                            });
                        })
                } else {
                    this.$Message.error(res.data.message);
                }
                this.info.formRelation = Number(this.info.formRelation);
                this.info.formType = Number(this.info.formType);
            })
        },
        changeProvince(val) {
            this.info.provinceId = val;
        },
        changeCity(val) {
            this.info.cityId = val;
        },
        changeArea(val) {
            this.info.areaId = val;
        },
        changeHospital(val) {
            this.info.hospitalId = val;
            var params = {};
            params.provinceCode = this.info.provinceId;
            params.cityCode = this.info.cityId;
            params.districtCode = this.info.areaId;
            params.hospitalType = 1;
            this.$axios
            .post(api.findKbaoHospitalRegisterDtoPage, params)
            .then(resp => {
                let list = resp.data.object;
                const hospitalList = [];
                list.map((el, i) => {
                    let tmpObj = {};
                    tmpObj.id = parseInt(el.id);
                    tmpObj.name = el.orgName;
                    hospitalList.push(tmpObj);
                });
                this.hospitalList = hospitalList;
                this.$forceUpdate();
            })
            .catch(err => {
                console.log(err);
            });
            if(this.info.hospitalId) {
                this.fromTypeChange (this.info.formType)
            }
        },
        submit(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    let msg = this.id ? "修改" : "添加";
                    let subApi = this.id
                        ? api.updatefFdsItems
                        : api.newfFdsItems;
                    let params = {};
                    params.id = this.id ? this.id : null;
                    params.serviceName = this.info.serviceName;
                    params.governmentsubsidycost = this.info.governmentsubsidycost;
                    params.amt = this.info.amt;
                    params.packagestatus = parseInt(this.info.packagestatus);
                    params.ascription = parseInt(this.info.ascription);
                    params.hospitalId =
                        this.info.hospitalId == 0 ||
                        this.info.hospitalId == undefined
                            ? ""
                            : this.info.hospitalId;
                    params.serviceDes = this.info.serviceDes;
                    params.provinceId =
                        this.info.provinceId == 0 ||
                        this.info.provinceId == undefined
                            ? ""
                            : parseInt(this.info.provinceId);
                    params.cityId =
                        this.info.cityId == 0 || this.info.cityId == undefined
                            ? ""
                            : parseInt(this.info.cityId);
                    params.areaId =
                        this.info.areaId == 0 || this.info.areaId == undefined
                            ? ""
                            : parseInt(this.info.areaId);
                    params.remarks = this.info.remarks;
                    params.numberYear = parseInt(this.info.numberYear);
                    params.executingAgency = parseInt(
                        this.info.executingAgency
                    );
                    params.nature = parseInt(this.info.nature);
                    // 服务 关联表单
                    params.formType = this.info.formType;
                    // 关联内容
                    params.formRelation = this.info.formRelation
                    console.log(this.info.hospitalId)
                    this.hospitalList.forEach(i =>{
                        if (i.id == this.info.hospitalId) {
                            this.hospitalName = i.name
                        } else {
                            this.hospitalName = ''
                        }
                    })
                    // console.log("传递数据",params);
                    // params.amountReceived = this.info.amountReceived;
                    if(params.governmentsubsidycost && params.amt){
                        if(params.governmentsubsidycost > params.amt){
                            this.$Message.error('政府补贴金额不得大于收费标准金额')
                            return
                        }
                        if(params.formType == null){
                            this.$Message.error('请选择关联表单')
                            return
                        }
                        if(params.formRelation == null){
                            this.$Message.error('请选择关联内容')
                            return
                        }
                    }
                    this.saveBtnLoading = true;
                    this.$axios
                        .post(subApi, params)
                        .then(resp => {
                            if (resp.data.success) {
                                this.$Message.success(msg + "成功");
                                //   公用方法
                                this.functionJS.queryNavgationTo(
                                    this,
                                    "/index/directory/serviceItems/list",
                                    {
                                        pageNo: this.pageNo,
                                        province: this.province,
                                        city: this.city,
                                        area: this.area,
                                        hospital: this.hospital,
                                        isBack: 2
                                    }
                                );
                            } else {
                                this.$Message.fail(msg + "失败，请重试");
                            }
                            this.saveBtnLoading = false;
                        })
                        .catch(err => {
                            this.saveBtnLoading = false;
                        });
                } else {
                    // this.$Message.error("数据不正确");
                }
            });
        },
        reback() {
            //   公用方法
            this.functionJS.queryNavgationTo(
                this,
                "/index/directory/serviceItems/list",
                {
                    pageNo: this.pageNo,
                    province: this.province,
                    city: this.city,
                    area: this.area,
                    hospital: this.hospital,
                    isBack: 2
                }
            );
        },
        alertMsg(msg) {
            this.$Message.error({
                render: h => {
                    return h("span", {
                        domProps: {
                            innerHTML: msg
                        },
                        style: { color: "#f00" }
                    });
                },
                duration: 3
            });
        },
        blurInput(e) {
            e.target.blur();
        }
    },
    watch: {
        info: {
            handler(n) {
                // console.log(n)
            },
            deep: true
        },
        formContent(n) {
            // console.log('formContent', n);
        },
        formTypeList(n) {
            // console.log('formTypeList', n);
        }
    }
};
</script>
<style lang="less" scoped>
.doctorreviewedit {
    padding: 10px;
    width: 100%;
    background: #ffffff;
    box-sizing: border-box;   
    .juzhong{
        width: 50%;
        margin: 0 auto;
    }
    .padding-l {
        padding-left: 5px;
    }
    .padding-r {
        padding-right: 5px;
    }
    .padding-t {
        padding: 15px 0;
        font-weight: 700;
        font-size: 20px;
        text-align: center;
    }
    .borderRight {
        border-right: 1px solid #e5e5e5;
    }
    .borderLeft {
        border-left: 1px solid #e5e5e5;
    }
    .borderBottom {
        border-bottom: 1px solid #e5e5e5;
    }
    .borderTop {
        border-top: 1px solid #e5e5e5;
    }
    .w-select {
        width: 200px;
    }
    .w-select-hos {
        width: 200px;
    }
    .w-input {
        width: 500px;
    }
    .w-number {
        width: 200px;
    }
    .req-icon {
        font-size: 18px;
        color: red;
        display: inline-block;
        height: 18px;
        width: 18px;
        text-align: center;
        line-height: 18px;
        vertical-align: middle;
    }
    .text-r {
        text-align: right;
    }
    .c-notice {
        color: #999999;
    }
    .btn {
        width: 50px;
        height: 32px;
        line-height: 18px;
    }
}
</style>
<style lang="less">
.upload-avatar {
    display: inline-block;
    vertical-align: middle;
    width: 32px !important;
    height: 32px !important;
    margin-bottom: 3px;
}
.avatar-box {
    position: relative;
    display: inline-block;
    .avatar-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.6);
        width: 32px;
        height: 32px;
    }
}
.avatar-box:hover .avatar-cover {
    display: block;
    text-align: center;
}
.avatar-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
    line-height: 32px;
}
.progress {
    width: 32px;
}
</style>